/**
 * @swagger
 * /api/room/practical-analysis:
 *   get:
 *     tags:
 *       - 房屋管理
 *     summary: 获取房屋实用性数据
 *     description: 获取房屋的实际使用情况、功能配置等基础数据
 *     responses:
 *       200:
 *         description: 成功获取实用性数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
                   type: integer
                   example: 200
                   description: 响应状态码
                 message:
                   type: string
                   example: "实用性分析获取成功"
                   description: 响应消息
 *                 data:
                   type: object
                   properties:
                     currentStatus:
                       type: object
                       description: 当前状态数据（仅包含可从数据库计算的真实数据）
                       properties:
                         landArea:
                           type: number
                           description: 土地面积（亩）
                         landAreaSquareMeters:
                           type: string
                           description: 土地面积（平方米）
                         currentFloorAreaRatio:
                           type: string
                           description: 当前容积率
                         currentBuildingDensity:
                           type: string
                           description: 当前建筑密度（%）
 *                     landCapacityAnalysis:
                       type: object
                       description: 土地容量分析（仅包含可从数据库计算的真实数据）
                       properties:
                         currentCapacity:
                           type: object
                           properties:
                             roomsPerAcre:
                               type: string
                               description: 每亩房间数
                             areaPerRoom:
                               type: string
                               description: 每房间面积
                             landUtilizationRate:
                               type: string
                               description: 土地利用率
                         # optimizedCapacity 和 efficiency 已移除（预测数据）
 *                     spaceConfigurationAssessment:
                       type: object
                       description: 空间配置评估（仅包含可从数据库计算的真实数据）
                       properties:
                         roomConfiguration:
                           type: object
                           properties:
                             publicRoomRatio:
                               type: string
                               description: 公用房间比例（%）
                             privateRoomRatio:
                               type: string
                               description: 私用房间比例（%）
                         spaceEfficiency:
                           type: object
                           properties:
                             usageRatio:
                               type: string
                               description: 使用率（%）
                             spaceWastage:
                               type: string
                               description: 空间浪费（平方米）
                         buildingLayout:
                           type: object
                           properties:
                             averageRoomsPerBuilding:
                               type: string
                               description: 平均每栋房间数
 *                     baseData:
 *                       type: object
 *                       properties:
 *                         totalRooms:
 *                           type: number
 *                           description: 总房间数
 *                         publicRooms:
 *                           type: number
 *                           description: 公用房间数
 *                         buildingCount:
 *                           type: number
 *                           description: 建筑数量
 *                         totalLandAcres:
 *                           type: number
 *                           description: 总土地面积（亩）
 *                         totalBuildingArea:
 *                           type: number
 *                           description: 总建筑面积
 *                         totalUsageArea:
 *                           type: number
 *                           description: 总使用面积
 *                         totalConstructionArea:
 *                           type: number
 *                           description: 总建设面积
 *       500:
 *         description: 服务器内部错误
 */
const { query } = require('../../../lib/db')
const { success, error, handleResponse } = require('../../../lib/response')
const { withCors } = require('../../../lib/cors')

/**
 * 处理房屋实用性数据请求
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function handler(req, res) {

  try {
    const sql = `
      SELECT 
        SUM(ZFJJS) as totalRooms,
        SUM(GYFJS) as publicRooms,
        SUM(LDS) as buildingCount,
        SUM(TJTDMS) as totalLandAcres,
        SUM(XXBXZJZMJ) as totalBuildingArea,
        SUM(XXBXZSYYMJ) as totalUsageArea,
        SUM(ZJZMJ) as totalConstructionArea
      FROM wd_zcgk_bxzyhz
    `

    const result = await query(sql)
    
    if (!result || result.length === 0) {
      return handleResponse(res, error('暂无房产数据', 404))
    }

    const data = result[0]
    const totalRooms = parseInt(data.totalRooms) || 0
    const publicRooms = parseInt(data.publicRooms) || 0
    const buildingCount = parseInt(data.buildingCount) || 0
    const totalLandAcres = parseFloat(data.totalLandAcres) || 0
    const totalBuildingArea = parseFloat(data.totalBuildingArea) || 0
    const totalUsageArea = parseFloat(data.totalUsageArea) || 0
    const totalConstructionArea = parseFloat(data.totalConstructionArea) || 0

    // 土地面积转换（1亩 ≈ 666.67平方米）
    const acreToSquareMeter = 666.67
    const totalLandSquareMeters = totalLandAcres * acreToSquareMeter

    // 计算当前容积率和建筑密度
    const currentFloorAreaRatio = totalLandSquareMeters > 0 ? totalConstructionArea / totalLandSquareMeters : 0
    const currentBuildingDensity = totalLandSquareMeters > 0 ? (totalBuildingArea / totalLandSquareMeters) * 100 : 0

    // 实用性数据
    const practicalAnalysis = {
      // 当前状态数据（仅包含可从数据库计算的真实数据）
      currentStatus: {
        landArea: totalLandAcres,
        landAreaSquareMeters: totalLandSquareMeters.toFixed(2),
        currentFloorAreaRatio: currentFloorAreaRatio.toFixed(2),
        currentBuildingDensity: currentBuildingDensity.toFixed(2)
      },

      // 土地容量分析（仅包含可从数据库计算的真实数据）
      landCapacityAnalysis: {
        currentCapacity: {
          roomsPerAcre: totalLandAcres > 0 ? (totalRooms / totalLandAcres).toFixed(2) : 0,
          areaPerRoom: totalRooms > 0 ? (totalUsageArea / totalRooms).toFixed(2) : 0,
          landUtilizationRate: currentBuildingDensity.toFixed(2)
        }
        // optimizedCapacity 和 efficiency 已移除（预测数据）
      },

      // 空间配置评估（仅包含可从数据库计算的真实数据）
      spaceConfigurationAssessment: {
        roomConfiguration: {
          publicRoomRatio: totalRooms > 0 ? ((publicRooms / totalRooms) * 100).toFixed(2) : 0,
          privateRoomRatio: totalRooms > 0 ? (((totalRooms - publicRooms) / totalRooms) * 100).toFixed(2) : 0
        },
        
        spaceEfficiency: {
          usageRatio: totalBuildingArea > 0 ? ((totalUsageArea / totalBuildingArea) * 100).toFixed(2) : 0,
          spaceWastage: totalBuildingArea > 0 ? (totalBuildingArea - totalUsageArea).toFixed(2) : 0
        },
        
        buildingLayout: {
          averageRoomsPerBuilding: buildingCount > 0 ? (totalRooms / buildingCount).toFixed(2) : 0
        }
      },

      // recommendations 部分已移除，仅返回数据

      // 原始数据
      baseData: {
        totalRooms,
        publicRooms,
        buildingCount,
        totalLandAcres,
        totalBuildingArea,
        totalUsageArea,
        totalConstructionArea
      }
    }

    return handleResponse(res, success(practicalAnalysis, '实用性数据获取成功'))

  } catch (err) {
    console.error('实用性数据接口错误:', err)
    return handleResponse(res, error('服务器内部错误', 500))
  }
}

export default withCors(handler, ['GET'])